package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.FanliBusiness;
import com.web.exiaodao.business.entity.FanliRules;
import com.web.exiaodao.business.repository.FanliBusinessRepository;
import com.web.exiaodao.business.repository.FanliRulesRepository;
import com.web.exiaodao.business.service.FanliRulesService;
import com.web.exiaodao.remote.vo.FanliBusinessVo;
import com.web.exiaodao.remote.vo.FanliRulesVo;

@Service("FanliRulesService")
@Transactional(readOnly = false)
public class FanliRulesServiceImpl extends BaseService<FanliRules> implements FanliRulesService {

	private static final Logger LOGGER = Logger.getLogger(FanliRulesServiceImpl.class);

	@Autowired
	private FanliRulesRepository fanliRulesRepository;
	@Autowired
	FanliBusinessRepository fanliBusinessRepository;
	
	/**
	 * 查询单条FanliRules信息
	 * //@param tId
	 * @return 返回单个FanliRules对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<FanliRules> findOne(Long modelId) throws BusinessException {
		FanliRules obj = new FanliRules();
		if(modelId != 0){
			obj = fanliRulesRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<FanliRules> xr = new XaResult<FanliRules>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->FanliRules");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的FanliRules数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象FanliRules集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<FanliRules>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<FanliRules> page = fanliRulesRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FanliRules.class), pageable);
		XaResult<Page<FanliRules>> xr = new XaResult<Page<FanliRules>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->FanliRules");
		return xr;
	}

	/**
	 * 分页查询状态status的FanliRules数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象FanliRules集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<FanliRules>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<FanliRules> page = fanliRulesRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FanliRules.class), pageable);
		XaResult<Page<FanliRules>> xr = new XaResult<Page<FanliRules>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->FanliRules");
		return xr;
	}

	/**
	 * 保存FanliRules信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<FanliRules> saveOrUpdate(FanliRules model) throws BusinessException {
		FanliRules obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = fanliRulesRepository.findOne(model.getId());
		}else{
			obj = new FanliRules();
		}
	obj.setCreateUser(XaUtil.isNotEmpty(model.getCreateUser()) ? model.getCreateUser() : obj.getCreateUser());
	    obj.setBusId(XaUtil.isNotEmpty(model.getBusId()) ? model.getBusId() : obj.getBusId());
	    obj.setBusfaliRate(XaUtil.isNotEmpty(model.getBusfaliRate()) ? model.getBusfaliRate() : obj.getBusfaliRate());
	    obj.setPlatformRaliRate(XaUtil.isNotEmpty(model.getPlatformRaliRate()) ? model.getPlatformRaliRate() : obj.getPlatformRaliRate());
	    obj.setUserFaliRate(XaUtil.isNotEmpty(model.getUserFaliRate()) ? model.getUserFaliRate() : obj.getUserFaliRate());
	    obj.setFaliDays(XaUtil.isNotEmpty(model.getFaliDays()) ? model.getFaliDays() : obj.getFaliDays());
		obj = fanliRulesRepository.save(obj);
		XaResult<FanliRules> xr = new XaResult<FanliRules>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改FanliRules状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回FanliRules对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<FanliRules> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<FanliRules> xr = new XaResult<FanliRules>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				FanliRules obj = fanliRulesRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = fanliRulesRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	//根据ＩＤ查询返利合约
	@Override
	public XaResult<FanliRulesVo> findFanliRulesById(Long modelId)
			throws BusinessException {
		XaResult<FanliRulesVo> xr = new XaResult<FanliRulesVo>();
		
		FanliRules obj = new FanliRules();
		FanliRulesVo vo = new FanliRulesVo();
		vo.setFanliRules(obj);
		List<FanliBusiness> list = fanliBusinessRepository.findBusinessNameListByStatusNot(XaConstant.Status.delete);
		if(XaUtil.isNotEmpty(list)){
			vo.setFanliBusiness(list);
			LOGGER.info("后台----->查询商家名列表-----");
		}else{
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		
		if(modelId != 0){
			obj = fanliRulesRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
			vo.setFanliRules(obj);
		}
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(vo);
			LOGGER.info("后台----->查询单个实体----->FanliRules");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	//查询返利合约列表
	@Override
	public XaResult<Page<FanliRulesVo>> findFanliRulesList(Integer status,
			Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		StringBuffer sql = new StringBuffer("SELECT fr.`id`,fb.`business_name`,fr.`busfali_rate`,fr.`platform_rali_rate`,fr.`user_fali_rate`,fr.`fali_days`,fr.`create_time`,fr.`status` ");
		sql.append("FROM `tb_xa_fanlirules` fr ");
		sql.append("LEFT JOIN `tb_xa_fanlibusiness` fb ON fb.`id` = fr.bus_id ");
		sql.append("WHERE fb.`status`<>").append(XaConstant.Status.delete).append(" AND fr.`status`<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_businessName"))){
			sql.append(" AND fb.business_name ").append(" like '%").append(filterParams.get("LIKE_businessName")).append("%' ");
		}
		sql.append(" ORDER BY fr.`create_time` DESC");
		List<Object[]> objs = this.query(sql.toString(), pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
		List<FanliRulesVo> vos = new ArrayList<FanliRulesVo>();
		for (Object[] obj : objs) {
			FanliRulesVo vo = new FanliRulesVo();
			FanliBusinessVo fb = new FanliBusinessVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			fb.setBusinessName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setBusfaliRate(XaUtil.isEmpty(obj[2])?0:Double.valueOf(obj[2].toString()));
			vo.setPlatformRaliRate(XaUtil.isEmpty(obj[3])?0:Double.valueOf(obj[3].toString()));
			vo.setUserFaliRate(XaUtil.isEmpty(obj[4])?0:Double.valueOf(obj[4].toString()));
			vo.setFaliDays(XaUtil.isEmpty(obj[5])?"":obj[5].toString());
			vo.setCreateTime(XaUtil.isEmpty(obj[6])?"":obj[6].toString());
			vo.setStatus(XaUtil.isEmpty(obj[7])?0:Integer.valueOf(obj[7].toString()));
			vo.setFanliBusinessVo(fb);
			vos.add(vo);
		}
		int count=objs.size();	
		Page<FanliRulesVo> page= new MyPage<FanliRulesVo>(pageable.getPageNumber(),pageable.getPageSize(),vos,count);
		XaResult<Page<FanliRulesVo>> xr=new XaResult<Page<FanliRulesVo>>();
		xr.setObject(page);
		return xr;
	}

}
